package javacource.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Create by chenhd on 2021/10/23.
 */
@Component
public class RedisOperator {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * set操作
     *
     * @param key
     * @param value
     * @return
     * @throws Exception
     */
    public boolean set(String key, String value) throws Exception {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            //log
            throw new Exception("redis call error.", e);
        }
    }

    /**
     * get操作
     *
     * @param key
     * @return
     * @throws Exception
     */
    public String get(String key) throws Exception {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            //log
            throw new Exception("redis call error.", e);
        }
    }

    /**
     * key值加1
     *
     * @param key
     * @return
     * @throws Exception
     */
    public boolean incr(String key) throws Exception {
        try {
            long effect = redisTemplate.opsForValue().increment(key, 1);
            return effect > 0;
        } catch (Exception e) {
            //log
            throw new Exception("redis call error.", e);
        }
    }

    /**
     * key值减1
     *
     * @param key
     * @return
     * @throws Exception
     */
    public boolean decr(String key) throws Exception {
        try {
            long count = redisTemplate.opsForValue().increment(key, -1);
            return count >= 0;
        } catch (Exception e) {
            //log
            throw new Exception("redis call error.", e);
        }
    }

    /**
     * 发布消息
     *
     * @param channel
     * @param msg
     */
    public void pub(String channel, String msg) {
        redisTemplate.convertAndSend(channel, msg);
    }
}
